package com.yint.tree;

/**
 * 顺序执行复合节点
 * <p>
 * Created by 殷田 on 2018/5/7.
 */
public class Sequence extends Composite {
    private int index = 0;

    @Override
    protected synchronized STATUS onTick(Tree tree) {
        int size = getSubs().size();
        for (int i = index; i < size; i++) {
            Leaf sub = getSubs().get(i);
            if (sub.entry(tree)) {
                STATUS state = sub.tick(tree);
                if (state == STATUS.SUCCEED) {
                    if (i >= (size - 1)) {
                        index = 0;
                        return STATUS.SUCCEED;
                    }
                    index++;
                } else {
                    if (state == STATUS.FAILED) {
                        index = 0;
                    }
                    return state;
                }
            } else {
                sub.leave(tree);
            }
        }
        index = 0;
        return STATUS.FAILED;
    }

    @Override
    protected void onLeave(Tree tree, STATUS state) {
        super.onLeave(tree, state);
        index = 0;
    }
}
